import React, { PureComponent } from "react";
import s from "./index.scss";
import { Flex ,Icon ,Toast} from "antd-mobile";
import {calculatorFlag} from 'actions/detail'
import {callApi} from 'app/utils'
import { connect } from "react-redux";
import AxFooter from "components/Footer";
import AxHeader from "components/AxHeader";
import Modal from 'antd/lib/Modal';
import {hashHistory} from 'React-Router'
@connect(
    state => ({
     
    }),
    {
      calculatorFlag
    }
  )

export default class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
       info:{},
       visible: false,
       dialogTitle:'',
       coinNumber:'未使用',//使用的奖励金金额
       coinIpt:'',
       couponId:'',
    };
    this.handleCancel = this.handleCancel.bind(this)
    this.showModal = this.showModal.bind(this)
    this.handleCoinIpt = this.handleCoinIpt.bind(this)
    this.handleCoinBtn = this.handleCoinBtn.bind(this)
    this.submit = this.submit.bind(this)
    this.linkCoupon = this.linkCoupon.bind(this)
  }

  linkCoupon(){
    hashHistory.push({
      pathname:'/projectList/Detail/coupon',
      query:{
        loanId: this.props.props.location.query.loanID,
        amount: this.state.info.investAmount, 
      }
    })
  }

  submit(){
    var loanInvestSubmitData
    if(localStorage.getItem('couponId')!=''&&localStorage.getItem('couponId')!=null&&localStorage.getItem('couponId')!=undefined){
      loanInvestSubmitData={
        token : JSON.parse(localStorage.getItem('userData')).token,
        loanId : localStorage.getItem('loanId'),
        investAmount : this.state.info.investAmount, 
        couponId :this.state.couponId,
        goldCoinAmount :this.state.coinNumber=='未使用'?0:this.state.coinNumber
       };
    }else{
      loanInvestSubmitData={
        token : JSON.parse(localStorage.getItem('userData')).token,
        loanId : this.props.props.location.query.loanID,
        investAmount : this.state.info.investAmount, 
        couponId :this.state.couponId,
        goldCoinAmount :this.state.coinNumber=='未使用'?0:this.state.coinNumber
       };
    }
     
    callApi('/loan/invest',loanInvestSubmitData,"POST").then((data)=>{
      if(data.success==true){
        localStorage.removeItem('val')
        localStorage.removeItem('type')
        localStorage.removeItem('loanId')
        localStorage.removeItem('couponId')
        localStorage.removeItem('amount')
      location.href = data.data.ret_url
        
      }
    })
  }

  handleCoinIpt(e){
    this.setState({
      coinIpt: e.target.value,
    });
  }
  handleCoinBtn(){
    if(this.state.info.goldAmount<this.state.coinIpt){
      Toast.info('金额不可大于奖励金')
      return false
    }
    if(this.state.coinIpt<=0){
      this.state.coinNumber = '未使用'
    }else{
      this.state.coinNumber = this.state.coinIpt
      
    }
      this.setState({
        visible: false,
      });
  }
  showModal() {
    this.setState({
      visible: true,
      dialogTitle:'使用奖励金'
    });

  }

  handleCancel(e) {
    this.setState({
      visible: false,
    });
  }

  componentDidMount() {
    let that = this
    let confirmData = {}
    if(localStorage.getItem('couponId')!=''&&localStorage.getItem('couponId')!=null&&localStorage.getItem('couponId')!=undefined){
      confirmData = {
        loanId: localStorage.getItem('loanId'),
        investAmount: localStorage.getItem('amount'),
        token: JSON.parse(localStorage.getItem('userData')).token,
      }
    }else{
      confirmData = {
        loanId: this.props.props.location.query.loanID,
        investAmount: this.props.props.location.query.number,
        token: JSON.parse(localStorage.getItem('userData')).token,
      }
    }
    callApi('/loan/invest/confirm',confirmData,'POST').then((data)=>{
      if(data.success==true){
        this.setState({info:data.data})
        if(localStorage.getItem('type')=='1'){
          this.state.info.type = 1
          this.state.info.cashAmount = localStorage.getItem('val')
        }else if(localStorage.getItem('type')=='2'){
          this.state.info.type = 2
          this.state.info.increaseRate = localStorage.getItem('val')
          this.state.info.cashAmount=0
        }
        that.forceUpdate()
        if(localStorage.getItem('couponId')!=''&&localStorage.getItem('couponId')!=null&&localStorage.getItem('couponId')!=undefined){
          let expectedprofitData = {
                  loanId: localStorage.getItem('loanId'),
                  couponId:localStorage.getItem('couponId'),
                  investAmount: localStorage.getItem('amount')
            }
          callApi('/loan/invest/expectedprofit',expectedprofitData,'POST').then((data)=>{
            let info = that.state.info
            info.allExpected = data.data.allExpected
            that.setState({
              info:info
            })
            that.forceUpdate(); 
          })
        }


      }
    })
  }
   //销毁时解绑事件
  componentWillUnmount() {
    //重写组件的setState方法，直接返回空
    this.setState = (state,callback)=>{
      return;
    };  
  }
  

  render() {
    let {info} = this.state
    return (
      <div className={`${s.payInfoBox}`}>
         <div>
          <AxHeader />
          <Flex className={`${s.investInfo}`} direction="column">
              <Flex.Item className={`${s.item} ${s.borderBot}`}>
                <Flex.Item className={`${s.left}`}>
                  <div>年化利率</div>
                  <div>{info.annualrate}%</div>
                </Flex.Item>
                <Flex.Item className={`${s.right}`}>
                  <div>融资金额(元)</div>
                  <div>¥{info.loanAmount}</div>
                </Flex.Item>
              </Flex.Item>
              <Flex.Item className={`${s.item}`}>
                <Flex.Item className={`${s.left}`}>
                  <div>融资期限</div>
                  <div>{info.term}</div>
                </Flex.Item>
                <Flex.Item className={`${s.right}`}>
                  <div>可投金额(元)</div>
                  <div>¥{info.investleft}</div>
                </Flex.Item>
              </Flex.Item>
          </Flex>

          <Flex className={`${s.block}`}></Flex>

          <Flex className={`${s.tipBox}`} direction="column">
            <Flex.Item className={`${s.top}`}>
              温馨提示
            </Flex.Item>
            <Flex.Item className={`${s.center}`}>
              安心投特提醒您，即日起至项目正式计息日（通常为满标日）期间，您将获得项目正常年化+1%的利息补贴奖励！
            </Flex.Item>
            <Flex.Item className={`${s.bot}`}>
              投资金额：<span className={`color2`}>￥{info.investAmount}</span>
            </Flex.Item>
          </Flex>

          <Flex className={`${s.block}`}></Flex>

          <Flex className={`${s.baseItem}`}>
            <Flex.Item className={`${s.left}`}>
              奖励金
            </Flex.Item>
            {info.goldAmount==0?<Flex.Item className={`${s.right}`}>
              无可用
            </Flex.Item>
            :<Flex.Item className={`${s.right}`} onClick={this.showModal}>
              <span className={`color1`}>{this.state.coinNumber}</span><Icon type="right"/>
            </Flex.Item>}
            
          </Flex>
          

          <Flex className={`${s.block}`}></Flex>

          <Flex className={`${s.baseItem}`}>
            <Flex.Item className={`${s.left}`}>
              优惠券
            </Flex.Item>
            {info.couponCount==0?<Flex.Item className={`${s.right}`}>
              无可用
            </Flex.Item>:
            <Flex.Item className={`${s.right}`}>
             
              <span className={`color1`} onClick={this.linkCoupon}>
                {info.type==1?info.cashAmount+'元':"加息"+info.increaseRate+"%"}
              </span><Icon type="right"/>
            </Flex.Item>}
            
          </Flex>

          <Flex className={`${s.block}`}></Flex>

          <Flex className={`${s.baseItem} mgtop10`}>
            <Flex.Item className={`${s.left}`}>
              实际支付：<span className={`color1`}>￥{info.investAmount-(this.state.coinNumber=='未使用'?0:this.state.coinNumber)-(info.cashAmount==undefined?0:info.cashAmount)}</span>
            </Flex.Item>
          </Flex>
          <Flex className={`${s.baseItem}`}>
            <Flex.Item className={`${s.left}`}>
              预计收益：<span className={`color1`}>￥{info.allExpected}</span>
            </Flex.Item>
          </Flex>

          <Flex className={`${s.baseItem} mgt20`}>
            <Flex.Item className={`${s.btn}`} onClick={this.submit}>
             确认支付
            </Flex.Item>
          </Flex>
          <Modal wrapClassName={`${s.vertical}`} title={this.state.dialogTitle} visible={this.state.visible}
           onCancel={this.handleCancel} footer={null}
           className={`${s.antmodal}`}
        >
          <div className={`${s.item}`}>最多可使用奖励金额(元)：<span className={`color2`}>¥{info.goldAmount}</span></div> 
          <div className={`${s.item}`}><input type="number"  onChange={this.handleCoinIpt}/>元</div> 
          <div className={`${s.item}`}>单笔投资10000元以下，按投资额的1%使用奖励金，单笔投资10000元以上（含）奖励金可任意使用。</div>
          <div className={`${s.btn}`} onClick={this.handleCoinBtn}>确认使用</div>
        </Modal>
        </div>

       

        <AxFooter base={true}/>
      </div>
    );

  }

}
